'use strict';

const crypto = require('crypto');

exports.main = async (event, context) => {
  const { action, ...params } = event;
  
  try {
    switch(action) {
      case 'createAdmin':
        return await createAdmin(params, context);
      case 'listUsers':
        return await listUsers(params, context);
      case 'updateUser':
        return await updateUser(params, context);
      case 'deleteUser':
        return await deleteUser(params, context);
      default:
        return { code: 400, msg: '不支持的操作' };
    }
  } catch(e) {
    console.error('云函数执行错误:', e);
    return { code: 500, msg: e.message || '服务器内部错误' };
  }
};

// 创建管理员用户
async function createAdmin(params, context) {
  const { username, password, nickname } = params;
  
  if(!username || !password) {
    return { code: 400, msg: '用户名和密码不能为空' };
  }
  
  try {
    const db = uniCloud.database();
    const usersCollection = db.collection('uni-id-users');
    
    // 检查用户是否已存在
    const existQuery = await usersCollection.where({
      username: username
    }).get();
    
    if(existQuery.data && existQuery.data.length > 0) {
      return { code: 400, msg: '用户已存在' };
    }
    
    // 加密密码
    const hashedPassword = crypto.createHash('sha256').update(password).digest('hex');
    
    // 创建用户
    const createRes = await usersCollection.add({
      username: username,
      password: hashedPassword,
      nickname: nickname || username,
      role: ['admin'],
      status: 0, // 0: 正常, 1: 禁用
      avatar: '/static/logo.png',
      email: '',
      mobile: '',
      create_date: Date.now(),
      last_login_date: null,
      last_login_ip: ''
    });
    
    if(createRes.id) {
      return {
        code: 0,
        data: {
          _id: createRes.id,
          username: username,
          nickname: nickname || username,
          role: ['admin']
        },
        msg: '管理员用户创建成功'
      };
    } else {
      return { code: 500, msg: '用户创建失败' };
    }
  } catch(e) {
    console.error('创建管理员失败:', e);
    return { code: 500, msg: '创建管理员失败: ' + e.message };
  }
}

// 获取用户列表
async function listUsers(params, context) {
  try {
    const db = uniCloud.database();
    const usersCollection = db.collection('uni-id-users');
    
    const result = await usersCollection
      .field({
        username: true,
        nickname: true,
        role: true,
        status: true,
        create_date: true,
        last_login_date: true,
        email: true,
        mobile: true
      })
      .orderBy('create_date', 'desc')
      .get();
    
    return {
      code: 0,
      data: result.data || [],
      msg: '获取用户列表成功'
    };
  } catch(e) {
    console.error('获取用户列表失败:', e);
    return { code: 500, msg: '获取用户列表失败: ' + e.message };
  }
}

// 更新用户信息
async function updateUser(params, context) {
  const { userId, updates } = params;
  
  if(!userId) {
    return { code: 400, msg: '用户ID不能为空' };
  }
  
  try {
    const db = uniCloud.database();
    const usersCollection = db.collection('uni-id-users');
    
    // 如果更新密码，需要加密
    if(updates.password) {
      updates.password = crypto.createHash('sha256').update(updates.password).digest('hex');
    }
    
    const updateRes = await usersCollection.doc(userId).update(updates);
    
    return {
      code: 0,
      data: updateRes,
      msg: '用户信息更新成功'
    };
  } catch(e) {
    console.error('更新用户失败:', e);
    return { code: 500, msg: '更新用户失败: ' + e.message };
  }
}

// 删除用户
async function deleteUser(params, context) {
  const { userId } = params;
  
  if(!userId) {
    return { code: 400, msg: '用户ID不能为空' };
  }
  
  try {
    const db = uniCloud.database();
    const usersCollection = db.collection('uni-id-users');
    
    const deleteRes = await usersCollection.doc(userId).remove();
    
    return {
      code: 0,
      data: deleteRes,
      msg: '用户删除成功'
    };
  } catch(e) {
    console.error('删除用户失败:', e);
    return { code: 500, msg: '删除用户失败: ' + e.message };
  }
}
